import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_diy_detail_page.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_building_index_terminal_settings_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'building_index_diy_list_response_bean.dart';
import 'building_index_diy_view_model.dart';

/// 楼层指引我制作的
class BuildingIndexDiyPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BuildingIndexDiyPage";

  @override
  BuildingIndexDiyPageState createState() => BuildingIndexDiyPageState();

}

class BuildingIndexDiyPageState
    extends BasePagerState<BuildingIndexDiyBean, BuildingIndexDiyPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {

  BuildingIndexDiyViewModel _viewModel;
  StreamSubscription _diyUpdateStreamSubscription;
  StreamSubscription _terminalCountUpdateStreamSubscription;

  ScrollController _scrollController;
  ///获取state
  static BuildingIndexDiyPageState of(BuildContext context) {
    final BuildingIndexDiyPageState result =
    context.findAncestorStateOfType<BuildingIndexDiyPageState>();
    return result;
  }

  double _imgContainerWidth = 0;
  double _imgContainerHeight = 0;


  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _viewModel = BuildingIndexDiyViewModel(this);
    _viewModel?.refresh();
    _diyUpdateStreamSubscription =
        VgEventBus.global.on<RefreshDiyPageEvent>()?.listen((event) {
          _scrollController.jumpTo(0);
         _viewModel?.refresh();
        });
    _terminalCountUpdateStreamSubscription =
        VgEventBus.global.on<RefreshBuildingIndexTerminalSettingsEvent>()?.listen((event) {
         _viewModel?.refresh();
        });

  }

  @override
  void dispose() {
    _diyUpdateStreamSubscription?.cancel();
    _terminalCountUpdateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      color: Colors.white,
      child: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        emptyWidget: _defaultEmptyCustomWidget("暂无内容"),
        errorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this,
            refreshBgColor: Colors.white,
            viewModel: _viewModel,
            child: _toGridPage())
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }


  Widget _toGridPage(){
    return GridView.builder(
      padding: EdgeInsets.only(
          left: 15,
          right: 15,
          bottom: getNavHeightDistance(context)
      ),
      itemCount: data?.length ?? 0,
      physics: BouncingScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 0,
        crossAxisSpacing: 5,
        childAspectRatio: 169.5 / 322,
      ),
      itemBuilder: (BuildContext context, int index) {
        return _toGridItemWidget(context,data?.elementAt(index));
      },
      controller: _scrollController,
    );
  }


  Widget _toGridItemWidget(BuildContext context, BuildingIndexDiyBean itemBean) {
    _imgContainerWidth = (ScreenUtils.screenW(context) - 30 - 5)/2;
    _imgContainerHeight = (_imgContainerWidth * 295)/169.5;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        BuildingIndexDiyDetailPage.navigatorPush(context, itemBean, false);
      },
      child: Column(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              height: _imgContainerHeight,
              width: _imgContainerWidth,
              color: Colors.white,
              child: VgCacheNetWorkImage(
                itemBean?.picurl ?? "",
                fit: BoxFit.fill,
                imageQualityType: ImageQualityType.high,),
            ),
          ),
          SizedBox(height: 4,),
          Container(
            height: 13,
            alignment: Alignment.centerLeft,
            child: Text(
              (itemBean?.hsnnum??0) > 0?"${itemBean?.hsnnum??0}个播放终端":"未指定播放终端",
              style: TextStyle(
                fontSize: 9,
                color: (itemBean?.hsnnum??0) > 0?
                      ThemeRepository.getInstance().getTextMinorGreyColor_808388()
                    : ThemeRepository.getInstance().getMinorRedColor_F95355()
              ),
            ),
          ),
          SizedBox(height: 10,),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
